package com.shibaobei.activity.service;

import com.shibaobei.activity.dao.ApplicationMapper;
import com.shibaobei.activity.model.Application;
import com.shibaobei.activity.model.TaskView;
import com.shibaobei.activity.model.Template;
import com.shibaobei.activity.model.User;
import com.shibaobei.activity.utils.UploadFileUtils;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.repository.ProcessDefinitionQuery;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.runtime.ProcessInstanceQuery;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Administrator on 2020/5/7 0007.
 */
@Service
public class FormflowService {
    @Autowired
    private FormTemplateService formTemplateService;
    @Autowired
    private ApplicationMapper applicationMapper;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private RepositoryService repositoryService;

    public void submit(String templateId, MultipartFile resource, HttpSession session) {


        try {
            //1、处理上传文件
            String targetPath = UploadFileUtils.copy(resource);

            //2、保存一个申请流程
            User user = (User) session.getAttribute("user");
            Template template = formTemplateService.getTemplateById(templateId);
            Application application = new Application();
            application.setApplicant(user);
            application.setApplyDate(new Date());
            application.setDocFilePath(targetPath);
            application.setStatus(Application.STATUS_APPROVING);
            application.setTemplate(template);
            String dateStr = new SimpleDateFormat("yyyy-MM_dd").format(application.getApplyDate());
            String title = template.getName()+"_"+user.getName()+"_"+dateStr;
            application.setTitle(title);
            applicationMapper.save(application);
            //3、启动流程实例
            String key = template.getPdKey();
            //设置流程变量
            Map<String,Object> variables = new HashMap<String,Object>();
            variables.put("application",application);
            variables.put("applicationId",application.getId());
            ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(key, variables);
            //4、办理第一个提交任务
            TaskQuery taskQuery = taskService.createTaskQuery();
            taskQuery.taskAssignee(user.getLoginName());
            taskQuery.processInstanceId(processInstance.getId());
            Task task = taskQuery.singleResult();
            String taskId = task.getId();
            taskService.complete(taskId);


        } catch (IOException e) {
            e.printStackTrace();
        }


    }
    public InputStream showPng(String deploymentId,String imageName) {
        return repositoryService.getResourceAsStream(deploymentId,imageName);
    }

    /**
     * 申请id（流程变量）查询任务
     * @param applicationId
     * @return
     */
    public Task findTaskByApplicationId(Integer applicationId) {
        TaskQuery query = taskService.createTaskQuery();
        //根据设置的流程变量进行过滤
        query.processVariableValueEquals("applicationId",applicationId);
        return query.singleResult();
    }

    public ProcessDefinition findPdByTask(Task task) {
        String processDefinitionId  = task.getProcessDefinitionId();
        ProcessDefinitionQuery query = repositoryService.createProcessDefinitionQuery();
        query.processDefinitionId(processDefinitionId);
        return query.singleResult();
    }

    /**
     *根据任务查询坐标
     * @param task
     * @return
     */
    public Map<String,Object> findCoordingByTask(Task task) {
        //获得流程定义id
        String processDefinitionId  = task.getProcessDefinitionId();
        //获得流程实例id
        String processInstanceId = task.getProcessInstanceId();
        //返回的流程定义对象中包含坐标信息
        ProcessDefinitionEntity processDefinition = (ProcessDefinitionEntity) repositoryService.getProcessDefinition(processDefinitionId);
        //获得流程实例
        ProcessInstanceQuery query = runtimeService.createProcessInstanceQuery();
        query.processInstanceId(processInstanceId);
        ProcessInstance instance = query.singleResult();

        //根据流程实例获得当前的活动节点
        String activityId = instance.getActivityId();
        ActivityImpl activity = processDefinition.findActivity(activityId);

        Map<String,Object> map = new HashMap<String ,Object>();
        map.put("x",activity.getX());
        map.put("y",activity.getY());
        map.put("width",activity.getWidth());
        map.put("height",activity.getHeight());

        return map;
    }

    /**
     * 根据当前登录人查询对应的任务列表
     * @param user
     * @return
     */
    public List<TaskView> findMyTaskList(User user) {
        //根据登录人查询任务列表
        TaskQuery query = taskService.createTaskQuery();
        query.taskAssignee(user.getLoginName());
        query.orderByTaskCreateTime().desc();
        List<Task> tasklist = query.list();
        List<TaskView> list = new ArrayList<>();
        //根据任务获取流程变量，封装taskview
        tasklist.forEach(task -> {
            String taskId = task.getId();
            Application application = (Application) taskService.getVariable(taskId, "application");
            TaskView taskView = new TaskView(task,application);
            list.add(taskView);
        });
        return  list;
    }
}
